package org.brownflat.lighthouse.ci.hudson;

import org.brownflat.lighthouse.ci.Build;
import org.brownflat.lighthouse.ci.Builder;
import org.brownflat.lighthouse.ci.Builds;
import org.brownflat.lighthouse.xml.XMLDocument;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class HudsonBuilder implements Builder<Builds, String> {
	public Builds build(String input) {
		XMLDocument document = new XMLDocument(input);
		HashMap namespaceContexts = new HashMap();
		namespaceContexts.put("atom", "http://www.w3.org/2005/Atom");
		document.setNamespaceContexts(namespaceContexts);
		
		List<XMLDocument> entryDocuments = document.documentsAt("/atom:feed/child::atom:entry");
		Builds builds = new Builds();
		
		for (Iterator iterator = entryDocuments.iterator(); iterator.hasNext();) {
			XMLDocument xmlDocument = (XMLDocument) iterator.next();
			Build build = buildBuild(xmlDocument);		
			builds.addBuild(build);
		}
		
		return builds;
	}

	private Build buildBuild(XMLDocument xmlDocument) {
		Build entry = new Build();
		entry.setProject(getProject(xmlDocument.selectValueAt("/atom:entry/atom:title")));
		entry.setBroken(xmlDocument.selectValueAt("/atom:entry/atom:title").contains("broken"));
		entry.setDate(getDate(xmlDocument.selectValueAt("/atom:entry/atom:updated")));
		return entry;
	}
	
	private String getProject(String title) {
		String[] elements = title.split(" ");
        return elements[0];
	}
	
	private Date getDate(String dateValue) {
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
		try {
			return fmt.parse(dateValue);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
	}
}
